﻿#include "SoundRecording.h"
#include "ui_SoundRecording.h"
#include <iostream>
#include <QFile>
#include <QDateTime>
#include "RecordingThread.h"
extern "C"
{
#include <libavdevice/avdevice.h>
#include <libavutil/avutil.h>
#include <libavcodec/avcodec.h>
}

CSoundRecording::CSoundRecording(QWidget *parent)
    : QWidget(parent)
    , m_ui(new Ui::SoundRecording)
	, m_pFmtCtx(nullptr)
	, m_pFile(nullptr)
	, m_pThread(new CRecordingThread)
{
    m_ui->setupUi(this);
	avdevice_register_all();
}

CSoundRecording::~CSoundRecording()
{
    delete m_ui;
}

void CSoundRecording::on_btnStartStop_clicked()
{
    if (m_ui->btnStartStop->isChecked())
    {
		startRecording(true);
		m_ui->btnStartStop->setText(QString("结束录"));
		m_ui->btnSuspend->setEnabled(true);
    }
    else
    {
		stopRecording(true);
		m_ui->btnStartStop->setText(QString("开始录"));
		m_ui->btnSuspend->setEnabled(false);
    }
}

void CSoundRecording::on_btnSuspend_clicked()
{
	if (m_ui->btnSuspend->isChecked())
	{
		m_ui->btnSuspend->setText(QString("继续"));
		stopRecording(false);
	}
	else
	{
		m_ui->btnSuspend->setText(QString("暂停"));
		startRecording(false);
	}
}

void CSoundRecording::startRecording(bool bIsOpenFile)
{
    AVInputFormat* pIFormat = av_find_input_format("alsa");
    int res = avformat_open_input(&m_pFmtCtx, "default", pIFormat, nullptr);
    if (res < 0)
    {
        std::cout << "打开设备失败!" << std::endl;
        return;
    }
    else
    {
        std::cout << "打开设备成功!" << std::endl;
    }
	if (bIsOpenFile)
	{
        QString strFilePath = QString("/home/ymm/audio_%1.aac")
			.arg(QDateTime::currentDateTime().toString("yyyyMMddhhmmss"));
		m_pFile = new QFile(strFilePath);
		if (!m_pFile->open(QIODevice::WriteOnly | QIODevice::Append))
		{
			m_ui->btnStartStop->setEnabled(false);
			return;
		}
		m_ui->labFileName->setText(QString("当前文件: ") + strFilePath);
	}
	
	if (m_pThread != nullptr)
	{
		m_pThread->setFormatContext(m_pFmtCtx);
		m_pThread->setRecordStatus(true);
		m_pThread->setFile(m_pFile);
        m_pThread->start();
	}
}

void CSoundRecording::stopRecording(bool bIsCloseFile)
{
	m_pThread->setFormatContext(nullptr);
	m_pThread->setRecordStatus(false);
	m_pThread->setFile(nullptr);
	m_pThread->quit();
	m_pThread->wait();
	if (m_pFmtCtx != nullptr)
	{
		avformat_close_input(&m_pFmtCtx);
		m_pFmtCtx = nullptr;
	}
	if (bIsCloseFile)
	{
		m_pFile->close();
	}
}

